package com.qall.media;

import static java.lang.Thread.yield;

public class ThreadTest {

    /**
     * 一个线程只会打印"A",一个线程只会打印"B",一个线程只会打印"C" 三个线程一起运行，交替打印，期望输出结果：ABCABCABCABC..
     *
     * @param args
     */
    private static volatile char currentPrint = 'E';

    public static void main(String[] args) {
        char a = 'A';
        char b = 'B';
        char c = 'C';

        Object obj = new Object();

        Thread threadA = new Thread(() -> {
            while (true) {

                synchronized (obj) {

                    if (!((currentPrint == 'C') || (currentPrint == 'E'))) {
                        try {
                            obj.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        System.out.print('A');
                        currentPrint = 'A';
                    }
                    try {
                        obj.notifyAll();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                }

            }
        });

        Thread threadB = new Thread(() -> {
            while (true) {


                synchronized (obj) {

                    if (!(currentPrint == 'A')) {
                        try {
                            obj.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        System.out.print('B');
                        currentPrint = 'B';
                    }

                    try {
                        obj.notifyAll();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }
        });
        Thread threadC = new Thread(() -> {

            synchronized (obj) {
                while (true) {

                    if (currentPrint != 'B') {
                        try {
                            obj.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    } else {
                        System.out.print('C');
                        currentPrint='C';
                    }
                    try {
                        obj.notifyAll();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }

        });
        threadA.start();
        threadB.start();
        threadC.start();

    }

    private static void print(char c) {
        System.out.println(c);
    }

}
